import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import { Point } from '@arcgis/core/geometry'
import { SimpleMarkerSymbol } from '@arcgis/core/symbols'

// 滑坡要素图层URL
const LANDSLIDE_FEATURE_LAYER_URL =
  'https://services7.arcgis.com/YJQokIlpj8q20MyY/arcgis/rest/services/LandslideRiskPointFeatureLayer/FeatureServer/0'

// 滑坡要素图层
let landslideLayer: FeatureLayer | null = null

/**
 * 初始化滑坡要素图层
 * @returns 滑坡要素图层
 */
export function initLandslideLayer(): FeatureLayer {
  if (!landslideLayer) {
    landslideLayer = new FeatureLayer({
      url: LANDSLIDE_FEATURE_LAYER_URL,
      outFields: ['*'],
      popupTemplate: {
        title: '{name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'Address', label: '发生地址' },
              { fieldName: 'occuredTime', label: '发生时间' },
              { fieldName: 'Description', label: '详情' },
              { fieldName: 'riskLevel', label: '风险等级' },
            ],
          },
        ],
      },
    })
  }
  return landslideLayer
}

/**
 * 获取滑坡要素列表
 * @returns 滑坡要素列表
 */
export async function getLandslideFeatures() {
  const layer = initLandslideLayer()

  try {
    const query = layer.createQuery()
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await layer.queryFeatures(query)
    return results.features
  } catch (error) {
    console.error('获取滑坡要素失败:', error)
    throw error
  }
}

/**
 * 添加滑坡要素
 * @param feature 滑坡要素数据
 * @returns 添加结果
 */
export async function addLandslideFeature(feature: {
  geometry: { longitude: number; latitude: number }
  attributes: {
    Address: string
    occuredTime: string
    name: string
    Description: string
    riskLevel: string
  }
}) {
  const layer = initLandslideLayer()

  try {
    // 创建点几何
    const point = new Point({
      longitude: feature.geometry.longitude,
      latitude: feature.geometry.latitude,
      spatialReference: { wkid: 4326 },
    })

    // 创建图形
    const graphic = new Graphic({
      geometry: point,
      attributes: feature.attributes,
    })

    // 添加要素
    const result = await layer.applyEdits({
      addFeatures: [graphic],
    })

    return result
  } catch (error) {
    console.error('添加滑坡要素失败:', error)
    throw error
  }
}

/**
 * 更新滑坡要素
 * @param objectId 要素ID
 * @param attributes 要素属性
 * @returns 更新结果
 */
export async function updateLandslideFeature(
  objectId: number,
  attributes: {
    Address?: string
    occuredTime?: string
    name?: string
    Description?: string
    riskLevel?: string
  },
) {
  const layer = initLandslideLayer()

  try {
    // 创建图形
    const graphic = new Graphic({
      attributes: {
        OBJECTID: objectId,
        ...attributes,
      },
    })

    // 更新要素
    const result = await layer.applyEdits({
      updateFeatures: [graphic],
    })

    return result
  } catch (error) {
    console.error('更新滑坡要素失败:', error)
    throw error
  }
}

/**
 * 删除滑坡要素
 * @param objectId 要素ID
 * @returns 删除结果
 */
export async function deleteLandslideFeature(objectId: number) {
  const layer = initLandslideLayer()

  try {
    // 创建图形
    const graphic = new Graphic({
      attributes: {
        OBJECTID: objectId,
      },
    })

    // 删除要素
    const result = await layer.applyEdits({
      deleteFeatures: [graphic],
    })

    return result
  } catch (error) {
    console.error('删除滑坡要素失败:', error)
    throw error
  }
}

/**
 * 获取滑坡要素默认符号
 * @returns 默认符号
 */
export function getLandslideSymbol() {
  return new SimpleMarkerSymbol({
    color: [226, 119, 40],
    outline: {
      color: [255, 255, 255],
      width: 2,
    },
    size: 12,
  })
}
